package com.laolang.pluto.framework.advice;

import com.laolang.pluto.common.core.domain.common.R;
import com.laolang.pluto.common.exception.BusinessException;
import com.laolang.pluto.common.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author laolang
 * @date 2021-08-01 22:22
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<R<Void>> businessExceptionHandler(BusinessException e) {
        R<Void> r = R.failed();
        r.setPropFromBusinessException(e);
        return ResponseEntity.status(HttpStatus.OK).body(r);
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<R<Void>> s(AccessDeniedException e) {
        return ResponseEntity.status(HttpStatus.OK).body(R.forbid());
    }

    /**
     * 兜底异常处理
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<R<Void>> exceptionHandler(Exception e) {
        R<Void> r = R.error();
        LogUtil.error(log, "未知异常");
        LogUtil.error(log, ExceptionUtils.getStackTrace(e));
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(r);
    }
}
